import CryptoJS from 'crypto-js';
import { fetchWrapper } from './common2';
import type { WarehouseData } from './dashboard';

const wmsPath = process.env.NEXT_PUBLIC_API_WMS_PATH;

const env = (process.env.NEXT_PUBLIC_APP_ENV || 'prod') as
  | 'dev'
  | 'staging'
  | 'prod';

const envTest =
  typeof window !== 'undefined' &&
  (new URL(window.location.href).searchParams.get('env') as typeof env);

const envFinale = env == 'prod' ? env : envTest || env;

const decryptData = (password?: string, secretKey?: string) => {
  let strp = CryptoJS.enc.Utf8.parse(secretKey || '');
  const encryptedBase64 = CryptoJS.enc.Base64.parse(password || '');
  const decrypted = CryptoJS.AES.decrypt(
    { ciphertext: encryptedBase64 },
    strp,
    {
      mode: CryptoJS.mode.ECB, // 使用 ECB 模式
      padding: CryptoJS.pad.Pkcs7, // 使用 PKCS7 填充方式
    },
  );
  return CryptoJS.enc.Utf8.stringify(decrypted);
};

const getUrlParams = (key: string) => {
  let res =
    typeof window !== 'undefined' &&
    new URL(window.location.href).searchParams.get(key);
  return res || '';
};

const getBaseInfo = async (warehouseId?: string) => {
  try {
    const res = await fetchWrapper<{
      warehouseList: WarehouseData[];
      earthParams: string;
      warehouseParams: string;
    }>(
      `${wmsPath}/wms/warehouse/banner-warehouse-v2?warehouseId=${warehouseId || ''}`,
      undefined,
      'GET',
    );

    const data = res?.warehouseList.find(
      (i) => i.warehouseId === Number(warehouseId),
    );

    return {...data, monitorServerAccount: decryptData(data?.monitorServerAccount, data?.monitorServerSecret ), monitorServerPassword: decryptData(data?.monitorServerPassword, data?.monitorServerSecret)};
  } catch (error) {}
};

export { getUrlParams, getBaseInfo, decryptData };
